// 二次封装axios
import axios from 'axios'
import { useUserStore } from '@/stores'
import { showFailToast, showToast } from 'vant'
import router from '@/router'

export const baseURL = 'https://consult-api.itheima.net/'
const request = axios.create({
  baseURL,
  timeout: 10000
})

request.interceptors.request.use(
  function (config) {
    const store = useUserStore()
    if (store?.user?.token) {
      config.headers.Authorization = `Bearer ${store?.user?.token}`
    }
    return config
  },
  function (err) {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  function (res) {
    // 判断接口返回code
    if (res.data?.code !== 10000) {
      showFailToast(res.data?.message)
      return Promise.reject(res.data)
    }
    return res.data
  },
  function (err) {
    // 登录超时 返回登录页
    if (err?.response?.status === 401) {
      showToast('登录超时，请重新登录')
      // 删除用户信息
      const store = useUserStore()
      store.clearUser()
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

export default request
